// 思路是创建一个图片，将file等于这个图片，然后创建一个canvas图层 ，将canvas等比例缩放，
//然后用canvas的drawImage将图片与canvas合起来，然后在把canvas的base64转成file即可
export default function ConvertImage(file) {
  return new Promise((resolve, reject) => {
    const fileName = file.name.substring(0, file.name.indexOf('.'));
    let reader = new FileReader(); //读取file
    reader.readAsDataURL(file);
    reader.onloadend = function (e) {
      let image = new Image(); //新建一个img标签（还没嵌入DOM节点)
      image.src = e.target.result; //将图片的路径设成file路径
      image.onload = function () {
        let canvas = document.createElement('canvas'),
          context = canvas.getContext('2d'),
          imageWidth = image.width,
          imageHeight = image.height,
          data = '';
        canvas.width = imageWidth;
        canvas.height = imageHeight;

        context.drawImage(image, 0, 0, imageWidth, imageHeight);
        data = canvas.toDataURL('image/jpeg');
        var newfile = dataURLtoFile(data, fileName + '.jpeg');
        resolve(newfile);
      };
    };
  });
}

function dataURLtoFile(dataurl, filename) {
  // base64转file对象
  let arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime }); //转成了jpeg格式
}
